package cc.iotkit.data.service;

import cc.iotkit.common.utils.MapstructUtils;
import cc.iotkit.data.dao.DeviceDailyReportRepository;
import cc.iotkit.data.dao.IJPACommData;
import cc.iotkit.data.manager.IDeviceDailyReportData;
import cc.iotkit.data.model.TbDeviceDailyReport;
import cc.iotkit.data.util.PredicateBuilder;
import cc.iotkit.model.device.DeviceDailyReport;
import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONUtil;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static cc.iotkit.data.model.QTbDeviceDailyReport.tbDeviceDailyReport;

@Primary
@Service
public class DeviceDailyReportDataImpl implements IDeviceDailyReportData, IJPACommData<DeviceDailyReport, Long> {
    private static Logger logger = LoggerFactory.getLogger(DeviceDailyReportDataImpl.class);
    @Autowired
    private JPAQueryFactory jpaQueryFactory;
    @Autowired
    private DeviceDailyReportRepository repository;

    @Override
    public JpaRepository getBaseRepository() {
        return repository;
    }

    @Override
    public Class getJpaRepositoryClass() {
        return TbDeviceDailyReport.class;
    }

    @Override
    public Class getTClass() {
        return DeviceDailyReport.class;
    }


    //@Transactional(rollbackFor = Exception.class)
    public void batchSave(List<DeviceDailyReport> data) {
        // 创建日期格式化对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<TbDeviceDailyReport> list=new ArrayList<>();
        data.forEach(d->{
            synchronized (this) {
                String deviceId = d.getDeviceId();
                // 格式化日期
                //String formattedDate =sdf.format(d.getReportDate());
                TbDeviceDailyReport row = repository.findFirstByReportDateAndDeviceId(sdf.format(d.getReportDate()), deviceId);

                if (row != null) {
                    if (d.getOnlineTimes() != null)
                        row.setOnlineTimes(d.getOnlineTimes());
                    if (d.getWorkingTimes() != null)
                        row.setWorkingTimes(d.getWorkingTimes());
                    if (d.getDistance() != null)
                        row.setDistance(d.getDistance());
                    if (d.getChargeTimes() != null)
                        row.setChargeTimes((row.getChargeTimes() == null ? 0 : row.getChargeTimes()));
                    if (d.getDischargeTimes() != null)
                        row.setDischargeTimes((row.getDischargeTimes() == null ? 0 : row.getDischargeTimes()));
                    if (d.getSquare() != null)
                        row.setSquare(d.getSquare() + (row.getSquare() == null ? 0 : row.getSquare()));
                    if (d.getDistributionTimes() != null)
                        row.setDistributionTimes(d.getDistributionTimes() + (row.getDistributionTimes() == null ? 0 : row.getDistributionTimes()));
                    if (d.getReceiveTimes() != null)
                        row.setReceiveTimes(d.getReceiveTimes() + (row.getReceiveTimes() == null ? 0 : row.getReceiveTimes()));
                    if (d.getAskTimes() != null)
                        row.setAskTimes(d.getAskTimes() + (row.getAskTimes() == null ? 0 : row.getAskTimes()));

                    //list.add(row);
                } else {
                    //list.add(MapstructUtils.convert(d,TbDeviceDailyReport.class));
                    row = MapstructUtils.convert(d, TbDeviceDailyReport.class);
                }
                logger.info("DailyReportInsert:"+ JSONUtil.toJsonStr(row));
                row.setDts(new DateTime());
                repository.save(row);
            }
        });
    }
    private Predicate buildPredicate(DeviceDailyReport data) {
        return PredicateBuilder.instance()
                .and(data.getId()!=null,()->tbDeviceDailyReport.id.eq(data.getId()))
                //.and(data.getReportDate()!=null, () -> tbDeviceDailyReport.reportDate.eq(data.getReportDate()))
                .and(data.getDeviceId()!=null, () -> tbDeviceDailyReport.deviceId.eq(data.getDeviceId()))
               // .and(StringUtils.isNotEmpty(data.getProductName()), () -> tbProduct.name.like("%"+data.getProductName()+"%"))
                //.and(StringUtils.isNotEmpty(data.getDeviceName()), () -> tbDeviceInfo.deviceName.like("%"+data.getDeviceName()+"%"))
                .build();
    }


    public List<DeviceDailyReport> findByConditions(DeviceDailyReport record) {
        List<DeviceDailyReport> rets=jpaQueryFactory.select(Projections.bean(DeviceDailyReport.class,
                        tbDeviceDailyReport.id))
                .from(tbDeviceDailyReport)
                .where(buildPredicate(record)).fetch();
        return rets;
    }


}
